<template>
  <a-modal v-model:open="open" :title="'编辑NoteBook'" centered :after-close="reset" :width="416" :ok-text="'编辑'" @ok="onOk">
    <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
      <a-form-item label="名称" name="name">
        <g-input v-model:value="formState.name" :search="false" placeholder="请输入名称" :maxlength="200" />
      </a-form-item>
      <a-form-item label="描述" name="remark">
        <a-textarea v-model:value="formState.remark" v-trim placeholder="请输入描述" class="h-88" :maxlength="200" show-count />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { type FormInstance, message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { ref } from 'vue'

  import { algoDevApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  export interface Props {
    afterCloseFn?: () => void
  }

  const props = withDefaults(defineProps<Props>(), {
    afterCloseFn: () => {}
  })

  const formRef = ref<FormInstance>()
  interface FormState {
    id?: string
    name: string
    remark: string
    [key: string]: any
  }
  const open = ref(false)
  const formState = ref<FormState>({
    id: '',
    name: '',
    remark: ''
  })

  const rules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ]
  }

  const reset = () => {
    formRef.value?.resetFields()
    formState.value = {
      id: '',
      name: '',
      remark: ''
    }
  }

  const confirmLoading = ref(false)
  const onOk = async () => {
    await formRef.value?.validateFields()
    confirmLoading.value = true
    try {
      await algoDevApi.editNotebook(formState.value, { isAddUid: true })
      confirmLoading.value = false
      message.success(`编辑成功`)
      open.value = false
      props.afterCloseFn()
    } catch (error) {
      confirmLoading.value = false
    }
  }

  defineExpose({
    open: (form?: FormState) => {
      if (form) {
        Object.assign(formState.value, form)
      }
      open.value = true
    }
  })
</script>
